import React, { useState, useEffect } from 'react'
import {
  Card,
  Space,
  Button,
  Select,
  InputNumber,
  Tooltip,
  Typography,
  Divider,
  Switch,
  Alert,
  message,
} from 'antd'
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  StopOutlined,
  SettingOutlined,
  DatabaseOutlined,
  ClockCircleOutlined,
  SaveOutlined,
  HistoryOutlined,
} from '@ant-design/icons'
import { useAppSelector, useAppDispatch } from '@/store'
import { Connection } from '@/types/connection'
import { ExecutionStatus } from './ExecutionProgress'

const { Text } = Typography
const { Option } = Select

interface ExecutionPanelProps {
  sql: string
  selectedConnection?: Connection | null
  execution?: ExecutionStatus | null
  onExecute?: (options: ExecutionOptions) => void
  onCancel?: () => void
  onSave?: () => void
  onConnectionChange?: (connectionId: string) => void
  disabled?: boolean
}

export interface ExecutionOptions {
  connectionId: string
  sql: string
  limit?: number
  timeout?: number
  autoCommit?: boolean
  explainOnly?: boolean
}

const ExecutionPanel: React.FC<ExecutionPanelProps> = ({
  sql,
  selectedConnection,
  execution,
  onExecute,
  onCancel,
  onSave,
  onConnectionChange,
  disabled = false,
}) => {
  const dispatch = useAppDispatch()
  const { connections } = useAppSelector(state => state.connection)
  
  // 执行选项状态
  const [limit, setLimit] = useState<number>(1000)
  const [timeout, setTimeout] = useState<number>(30)
  const [autoCommit, setAutoCommit] = useState<boolean>(true)
  const [explainOnly, setExplainOnly] = useState<boolean>(false)
  const [showAdvanced, setShowAdvanced] = useState<boolean>(false)

  // 检查是否可以执行
  const canExecute = !disabled && 
                    selectedConnection && 
                    sql.trim() && 
                    (!execution || execution.status !== 'running')

  const canCancel = execution?.status === 'running'

  // 处理执行
  const handleExecute = () => {
    if (!canExecute || !selectedConnection) {
      message.warning('请选择数据库连接并输入SQL语句')
      return
    }

    const options: ExecutionOptions = {
      connectionId: selectedConnection.id,
      sql: sql.trim(),
      limit,
      timeout: timeout * 1000, // 转换为毫秒
      autoCommit,
      explainOnly,
    }

    onExecute?.(options)
  }

  // 处理取消
  const handleCancel = () => {
    onCancel?.()
  }

  // 处理连接变化
  const handleConnectionChange = (connectionId: string) => {
    onConnectionChange?.(connectionId)
  }

  // 快捷键处理
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      // Ctrl+Enter 或 F5 执行
      if ((event.ctrlKey && event.key === 'Enter') || event.key === 'F5') {
        event.preventDefault()
        if (canExecute) {
          handleExecute()
        }
      }
      // Esc 取消执行
      else if (event.key === 'Escape' && canCancel) {
        handleCancel()
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [canExecute, canCancel])

  return (
    <Card 
      size="small" 
      style={{ marginBottom: 16 }}
      bodyStyle={{ padding: '12px 16px' }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        {/* 左侧：主要控制 */}
        <Space size="middle">
          {/* 数据库连接选择 */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <DatabaseOutlined />
            <Select
              placeholder="选择数据库连接"
              style={{ width: 200 }}
              value={selectedConnection?.id}
              onChange={handleConnectionChange}
              disabled={disabled}
            >
              {connections.map(conn => (
                <Option key={conn.id} value={conn.id}>
                  <Space>
                    <span>{conn.name}</span>
                    <Text type="secondary" style={{ fontSize: 11 }}>
                      {conn.host}:{conn.port}
                    </Text>
                  </Space>
                </Option>
              ))}
            </Select>
          </div>

          <Divider type="vertical" />

          {/* 执行控制按钮 */}
          <Space>
            <Tooltip title="执行SQL (Ctrl+Enter / F5)">
              <Button
                type="primary"
                icon={<PlayCircleOutlined />}
                onClick={handleExecute}
                disabled={!canExecute}
                loading={execution?.status === 'running'}
              >
                执行
              </Button>
            </Tooltip>

            {canCancel && (
              <Tooltip title="取消执行 (Esc)">
                <Button
                  danger
                  icon={<StopOutlined />}
                  onClick={handleCancel}
                >
                  取消
                </Button>
              </Tooltip>
            )}

            <Tooltip title="仅解释执行计划">
              <Button
                icon={<HistoryOutlined />}
                onClick={() => {
                  setExplainOnly(true)
                  handleExecute()
                }}
                disabled={!canExecute}
              >
                解释
              </Button>
            </Tooltip>
          </Space>
        </Space>

        {/* 右侧：选项和设置 */}
        <Space>
          {/* 快速设置 */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
              <Text type="secondary" style={{ fontSize: 12 }}>限制:</Text>
              <InputNumber
                size="small"
                min={1}
                max={10000}
                value={limit}
                onChange={(value) => setLimit(value || 1000)}
                style={{ width: 80 }}
                disabled={disabled}
              />
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
              <ClockCircleOutlined style={{ fontSize: 12, color: '#666' }} />
              <InputNumber
                size="small"
                min={1}
                max={300}
                value={timeout}
                onChange={(value) => setTimeout(value || 30)}
                style={{ width: 60 }}
                disabled={disabled}
                addonAfter="s"
              />
            </div>
          </div>

          <Divider type="vertical" />

          {/* 高级设置切换 */}
          <Tooltip title="高级设置">
            <Button
              type="text"
              icon={<SettingOutlined />}
              onClick={() => setShowAdvanced(!showAdvanced)}
            />
          </Tooltip>

          {/* 保存按钮 */}
          {onSave && (
            <Tooltip title="保存脚本">
              <Button
                type="text"
                icon={<SaveOutlined />}
                onClick={onSave}
                disabled={disabled}
              />
            </Tooltip>
          )}
        </Space>
      </div>

      {/* 高级设置面板 */}
      {showAdvanced && (
        <div style={{ 
          marginTop: 12, 
          paddingTop: 12, 
          borderTop: '1px solid #f0f0f0' 
        }}>
          <Space size="large">
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Text style={{ fontSize: 12 }}>自动提交:</Text>
              <Switch
                size="small"
                checked={autoCommit}
                onChange={setAutoCommit}
                disabled={disabled}
              />
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Text style={{ fontSize: 12 }}>仅解释:</Text>
              <Switch
                size="small"
                checked={explainOnly}
                onChange={setExplainOnly}
                disabled={disabled}
              />
            </div>
          </Space>

          {!autoCommit && (
            <Alert
              message="注意：关闭自动提交后，需要手动提交事务"
              type="warning"
              showIcon
              style={{ marginTop: 8, fontSize: 12 }}
            />
          )}
        </div>
      )}

      {/* 连接状态提示 */}
      {selectedConnection && (
        <div style={{ 
          marginTop: 8, 
          fontSize: 11, 
          color: '#666',
          display: 'flex',
          alignItems: 'center',
          gap: 4,
        }}>
          <span>已连接到:</span>
          <Text code style={{ fontSize: 11 }}>
            {selectedConnection.name} ({selectedConnection.host}:{selectedConnection.port}/{selectedConnection.database})
          </Text>
        </div>
      )}
    </Card>
  )
}

export default ExecutionPanel